package com.woniuxy.gateway.filter;

import cn.hutool.jwt.JWTUtil;
import com.alibaba.nacos.api.utils.StringUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.common.dto.WhiteDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import rx.schedulers.Schedulers;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户认证
 */
@Slf4j
@Order(1)//值越小优先级越高
@Component
public class LoginFilter implements GlobalFilter {
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private ReactiveStringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //白名单,放行
        String path = exchange.getRequest().getPath().toString();
        if("/login".equals(path)){
            return chain.filter(exchange);
        }
//        Mono<List<WhiteDto>> whiteList = redisTemplate.opsForValue().get("whiteList").map(jsonString -> {
//            try {
//                // 将 JSON 字符串反序列化为 List<White>
//                return objectMapper.readValue(jsonString, new TypeReference<List<WhiteDto>>() {
//                });
//            } catch (IOException e) {
//                // 处理异常
//                e.printStackTrace();
//                return null; // 或者抛出一个 RuntimeException
//            }
//        });
//        List<WhiteDto> whiteDtos = new ArrayList<>();
//        whiteList.subscribe(
//                list->{
//                    for (WhiteDto whiteDto : list) {
//                        whiteDtos.add(whiteDto);
//                    }
//                }
//        );
//        for (WhiteDto whiteDto : whiteDtos) {
//            if(whiteDto.getName().equals(path)){
//                return chain.filter(exchange);
//            }
//        }
//        log.info("whiteList");

        //从请求头获取token
        String token = exchange.getRequest().getHeaders().getFirst("token");

//        return redisTemplate.opsForValue().get(token).flatMap(t->{
//            if(StringUtils.isBlank(t)){
//                return getVoidMono(exchange);
//            }
//            //校验token，成功：放行  失败：提示认证失败
//            try {
//                boolean verify = JWTUtil.verify(token, "woniu".getBytes());
//                if(!verify){
//                    return getVoidMono(exchange);
//                }
//            } catch (Exception e) {
//                log.error("login Filter is error:{}, token:{}", e, token);
//                return getVoidMono(exchange);
//            }
//
//            // TODO 刷新redis中token的时间
//            //redisTemplate.opsForValue().set(token,token,Duration.ofMinutes(30)).subscribe();
//
//            redisTemplate.expire(token,Duration.ofDays(30)).subscribe();
//
//            //放行
//            return chain.filter(exchange);
//        });
        if(StringUtils.isBlank(token)){
            return getVoidMono(exchange);
        }
        return redisTemplate.hasKey(token).flatMap(b->{
            if(b) {
                //校验token，成功：放行  失败：提示认证失败
                try {
                    boolean verify = JWTUtil.verify(token, "woniu".getBytes());
                    if (!verify) {
                        return getVoidMono(exchange);
                    }
                } catch (Exception e) {
                    log.error("login Filter is error:{}, token:{}", e, token);
                    return getVoidMono(exchange);
                }
                redisTemplate.expire(token, Duration.ofDays(30)).subscribe();

            }
            return chain.filter(exchange);
        });

    }


    private static Mono<Void> getVoidMono(ServerWebExchange exchange) {
        log.info("login is error");
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
//        String jsonStr = "{\"status\":\"400\", \"msg\":\"token非法\"}";
//        byte[] bytes = jsonStr.getBytes(StandardCharsets.UTF_8);
//        DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
//        return exchange.getResponse().writeWith(Flux.just(buffer));
    }
}
